package com.scoressystem.controller;


import com.scoressystem.pojo.Subjects;
import com.scoressystem.service.SubjectsService;
import com.scoressystem.utils.Results;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/subjects")
public class SubjectsController {

    @Resource
    private SubjectsService subjectsService;

    @RequestMapping("/getAllSubject")
    public Results<List<Subjects>> SubjectPage(@RequestParam(value = "name", defaultValue = "") String name,
                                              @RequestParam(value = "page", defaultValue = "1") int pageIndex,
                                              @RequestParam(value = "limit", defaultValue = "5") int pageSize) {

        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("pageStart", (pageIndex - 1) * pageSize);
        map.put("pageSize", pageSize);

        List<Subjects> Subjects = subjectsService.selectAllSubjectsByPage(map);
        long total = subjectsService.selectAllSubjectsCount(map);
        return new Results<>("0", "查询成功", Subjects, total);

    }

    @RequestMapping("/updateSubject")
    public Results<String> updateSubject(Subjects Subject) {
        int result = subjectsService.updateSubject(Subject);
        if (result > 0) {
            return new Results<>("0", "更新成功");
        } else {
            return new Results<>("1", "更新失败");
        }
    }

    @RequestMapping("/deleteSubject")
    public Results<String> deleteSubject(@RequestParam("id") Integer SubjectNo) {
        int result = subjectsService.deleteSubjectById(SubjectNo);
        if (result > 0) {
            return new Results<>("0", "删除成功");
        } else {
            return new Results<>("1", "删除失败");
        }
    }

    @RequestMapping("/addSubject")
    public Results<String> addSubject(Subjects Subject) {
        Subjects subjectsByName = subjectsService.getSubjectsByName(Subject.getName());
        if (subjectsByName != null) {
            return new Results<>("4", "课程已存在");
        }

        int result = subjectsService.addSubject(Subject);

        if (result > 0) {
            return new Results<>("0", "添加成功");
        } else {
            return new Results<>("1", "添加失败");
        }
    }

    @PostMapping("/subjectSelect")
    public Results<List<Subjects>> subjectSelect() {
        List<Subjects> subjectsList = subjectsService.getAllSubjects();
        if (subjectsList.isEmpty()) {
            return new Results<>("1", "没有找到相关课程");
        }
        return new Results<>("0", "查询成功", subjectsList);
    }
}
